package com.yan.club.sys.control;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yan.club.result.Result;
import com.yan.club.sys.dto.SysRoleDto;
import com.yan.club.sys.dto.SysUserDto;
import com.yan.club.sys.model.SysCommunity;
import com.yan.club.sys.model.SysRole;
import com.yan.club.sys.model.SysUser;
import com.yan.club.sys.model.SysUserRole;
import com.yan.club.sys.service.SysCommunityService;
import com.yan.club.sys.service.SysRoleService;
import com.yan.club.sys.service.SysUserService;
import com.yan.club.sys.vo.RoleMenuTreeselectVo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static com.yan.club.auth.utils.SecurityUtil.getUser;
import static com.yan.club.result.ResultCode.INTERNAL_SERVER_ERROR;

/**
 * @author 彦
 * @since 2024/2/7 11:10
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController {

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysCommunityService sysCommunityService;

    @Resource
    private SysUserService sysUserService;

    @PreAuthorize("@check.hasAuthority('system:role:list')")
    @GetMapping("/list")
    public Result<PageInfo<SysRole>> list(SysRoleDto role) {
        PageHelper.startPage(role.getPageNum(), role.getPageSize(), true);

        List<SysRole> list = sysRoleService.selectRoleList(role);

        return Result.success(new PageInfo<>(list));
    }

    /**
     * 新增角色
     */
    @PreAuthorize("@check.hasAuthority('system:role:add')")
    @PostMapping("/save")
    public Result<String> save(@Validated @RequestBody SysRoleDto role) {
        if (sysRoleService.checkRoleNameUnique(role)) {
            return Result.error(INTERNAL_SERVER_ERROR.code,
                    "新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (sysRoleService.checkRoleKeyUnique(role)) {
            return Result.error(INTERNAL_SERVER_ERROR.code,
                    "新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(getUser().getUserName());
        role.setUpdateTime(new Date());

        return sysRoleService.insertRole(role);
    }

    /**
     * 修改保存角色
     */
    @PreAuthorize("@check.hasAuthority('system:role:edit')")
    @PutMapping
    public Result<String> update(@Validated @RequestBody SysRoleDto role) {
        sysRoleService.checkRoleAllowed(role);
        sysRoleService.checkRoleDataScope(role.getRoleId());

//        if (sysRoleService.checkRoleNameUnique(role)) {
//            return Result.error(INTERNAL_SERVER_ERROR.code,
//                    "修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
//        } else if (!sysRoleService.checkRoleKeyUnique(role)) {
//            return Result.error(INTERNAL_SERVER_ERROR.code,
//                    "修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
//        }

        role.setUpdateBy(getUser().getUserName());

        return sysRoleService.updateRole(role);
    }

    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize("@check.hasAuthority('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public Result<SysRole> getInfo(@PathVariable Long roleId) {
        sysRoleService.checkRoleDataScope(roleId);
        return Result.success(sysRoleService.selectRoleById(roleId));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@check.hasAuthority('system:role:edit')")
    @PutMapping("/changeStatus")
    public Result<String> changeStatus(@RequestBody SysRole role) {
        sysRoleService.checkRoleAllowed(role);
        sysRoleService.checkRoleDataScope(role.getRoleId());
        role.setUpdateBy(getUser().getUserName());

        return sysRoleService.updateRoleStatus(role);

    }

    /**
     * 删除角色
     */
    @PreAuthorize("@check.hasAuthority('system:role:remove')")
    @DeleteMapping("/{roleIds}")
    public Result<String> delete(@PathVariable Long[] roleIds) {
        sysRoleService.deleteRoleByIds(roleIds);
        return Result.success();
    }

    /**
     * 获取对应角色部门树列表
     */
    @PreAuthorize("@check.hasAuthority('system:role:query')")
    @GetMapping(value = "/deptTree/{roleId}")
    public Result<RoleMenuTreeselectVo> deptTree(@PathVariable("roleId") Long roleId) {
        RoleMenuTreeselectVo roleMenuTreeselectVo = new RoleMenuTreeselectVo();
        roleMenuTreeselectVo.setCheckedKeys(sysCommunityService.selectDeptListByRoleId(roleId));
        roleMenuTreeselectVo.setDepts(sysCommunityService.selectDeptTreeList(new SysCommunity()));
        return Result.success(roleMenuTreeselectVo);
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@check.hasAuthority('system:role:edit')")
    @PutMapping("/dataScope")
    public Result<String> dataScope(@RequestBody SysRole role) {
        sysRoleService.checkRoleAllowed(role);
        sysRoleService.checkRoleDataScope(role.getRoleId());
        sysRoleService.authDataScope(role);

        return Result.success();
    }

    /**
     * 查询已分配用户角色列表
     */
    @PreAuthorize("@check.hasAuthority('system:role:list')")
    @GetMapping("/authUser/allocatedList")
    public Result<PageInfo<SysUser>> allocatedList(SysUserDto user) {
        PageHelper.startPage(user.getPageNum(), user.getPageSize(), true);
        List<SysUser> list = sysUserService.selectAllocatedList(user);
        return Result.success(new PageInfo<>(list));
    }

    /**
     * 查询未分配用户角色列表
     */
    @PreAuthorize("@check.hasAuthority('system:role:list')")
    @GetMapping("/authUser/unallocatedList")
    public Result<PageInfo<SysUser>> unallocatedList(SysUserDto user) {
        PageHelper.startPage(user.getPageNum(), user.getPageSize(), true);
        List<SysUser> list = sysUserService.selectUnallocatedList(user);
        return Result.success(new PageInfo<>(list));
    }

    /**
     * 取消授权用户
     */
    @PreAuthorize("@check.hasAuthority('system:role:edit')")
    @PutMapping("/authUser/cancel")
    public Result<String> cancelAuthUser(@RequestBody SysUserRole userRole) {
        return sysRoleService.deleteAuthUser(userRole);
    }

    /**
     * 批量选择用户授权
     */
    @PreAuthorize("@check.hasAuthority('system:role:edit')")
    @PutMapping("/authUser/selectAll")
    public Result<String> selectAuthUserAll(Long roleId, Long[] userIds) {
        sysRoleService.checkRoleDataScope(roleId);

        sysRoleService.insertAuthUsers(roleId, userIds);

        return Result.success();
    }
}
